package com.chuangke.sms.sender.dydxwg;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.chuangke.sms.model.SMSModel;
import com.chuangke.sms.sender.SMSSender;

import cn.hutool.core.util.StrUtil;

@Service
public class DydxwgSender implements SMSSender {

    private static final Logger logger = LoggerFactory.getLogger(DydxwgSender.class);

    private static final String URL_FORMATE = "%s?yhid=%s&yhmm=%s&phone=%s&msg=%s";

    @Autowired
    private DydxwgConfig dydxwgConfig;

    @Override
    public List<SMSModel> send(SMSModel... smsModels) {
        if (smsModels.length == 0) {
            return new ArrayList<>();
        }

        List<SMSModel> reponseSmsModelList = new ArrayList<>();
        for (SMSModel smsModel : smsModels) {
            long start = System.currentTimeMillis();

            String url = getSendUrl(smsModel.getTelphone(), smsModel.getMessage());
            String result = null;
            if (!StrUtil.isBlank(smsModel.getTelphone()) && !StrUtil.isBlank(smsModel.getMessage())) {
                result = sendUrlRequest(url);
            } else {
                result = "手机号或消息为空，不能发送短信.";
            }

            smsModel.setRequest(dydxwgConfig.getUrl());
            smsModel.setParams(url);
            smsModel.setReponse(result);
            smsModel.setTime(System.currentTimeMillis() - start);

            reponseSmsModelList.add(smsModel);
        }
        return reponseSmsModelList;
    }

    /**
     * @return
     * @Description: 根据传进来的url发送短线，并返回消息体
     */
    private String sendUrlRequest(String sendUrl) {
        HttpURLConnection conn = null;
        BufferedReader in = null;
        StringBuilder resultMessage = new StringBuilder();
        URL url = null;
        try {
            url = new URL(sendUrl);
            conn = (HttpURLConnection) url.openConnection();
            conn.setConnectTimeout(dydxwgConfig.getConntimeout());
            conn.setReadTimeout(dydxwgConfig.getReadtimeout());
            conn.setRequestMethod("POST");
            conn.setDoOutput(true);
            conn.setRequestProperty("User-Agent", "directclient");

            in = new BufferedReader(new InputStreamReader(conn.getInputStream(), StandardCharsets.UTF_8));

            String inputLine;
            while ((inputLine = in.readLine()) != null) {
                resultMessage.append(inputLine);
            }
        } catch (Exception e) {
            logger.error("exception", e);
            return e.getMessage();
        } finally {
            if (conn != null) {
                conn.disconnect();
            }
            if (in != null) {
                try {
                    in.close();
                } catch (IOException ignored) {
                }
            }
        }
        return resultMessage.toString();
    }

    /**
     * @param msg
     * @return
     * @Description: 获取发送url
     */
    private String getSendUrl(String telphone, String msg) {
        String urlMsg = msg;
        try {
            urlMsg = URLEncoder.encode(msg, "GBK");
        } catch (UnsupportedEncodingException e) {
            logger.error(e.getMessage());
        }
        return String.format(URL_FORMATE, dydxwgConfig.getUrl(), dydxwgConfig.getYhid(), dydxwgConfig.getYhmm(),
                telphone, urlMsg);
    }

}
